<?php

namespace addons\qingdongams\controller;

use addons\qingdongams\model\Account;
use addons\qingdongams\model\Contract as ContractModel;
use addons\qingdongams\model\ContractFile;
use addons\qingdongams\model\ContractOther;
use addons\qingdongams\model\ContractProduct;
use addons\qingdongams\model\ExamineRecord;
use addons\qingdongams\model\Flow;
use addons\qingdongams\model\FormField;
use addons\qingdongams\model\OperationLog;
use addons\qingdongams\model\Ratio;
use addons\qingdongams\model\Receivables;
use addons\qingdongams\model\Message;
use addons\qingdongams\model\Staff;
use addons\qingdongams\model\CustomerProduct;
use PhpOffice\PhpWord\TemplateProcessor;
use think\Db;
use think\Exception;

/**
 * 订单接口
 */
class Contract extends StaffApi
{
    protected $noNeedLogin = [];
    protected $noNeedRight = [];

    //创建订单
    public function addContract()
    {
        $params = $this->request->post();

        // 表单验证
        if (($result = $this->qingdongamsValidate($params, get_class(), 'create')) !== true) {
            $this->error($result);
        }
        $result = FormField::checkFields(FormField::CONTRACT_TYPE,$params);
        if ($result !== true) {
            $this->error($result);
        }
        Db::startTrans();
        try {
            $result = ContractModel::createContract($params);
            $customerModel = new \addons\qingdongams\model\Customer();
            $customerInfo = $customerModel->where(['id' => $params['customer_id']])->find();
            if (!in_array($customerInfo['follow'], ['准备付款', '已经购买'])) {
                $customerModel->where(['id' => $params['customer_id']])->update(['follow' => '准备购买']);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('添加订单成功');
        }
    }


    //获取select订单列表
    public function getSelectList()
    {
        $limit = input("limit/d", 10);
        $customer_id = input('customer_id');
        $where = [];
        $name = input('name');
        if ($name) {
            $where['num'] = ['like', "%{$name}%"];
        }
        if ($customer_id) {
            $where['customer_id'] = $customer_id;
        }
        $where['owner_staff_id'] = ['in', Staff::getMyStaffIds()];
        $records = ContractModel::where($where)->with(['ownerStaff'])->field('id,name,num,order_date,money,owner_staff_id')->paginate($limit);
        $this->success('请求成功', $records);
    }


    //获取订单编号
    public function getContractNumber()
    {
        $this->success('请求成功', ['number' => getItemNumber('contract')]);
    }

    //获取订单列表
    public function getList()
    {
        $limit = input("limit/d", 10);
        $customer_id = input('customer_id');

        $name = input('name');
        $is_invoice = input('is_invoice');//1是 2否 是否开发票
        $params = $this->request->post();

        $where= FormField::updateWhereField(FormField::CONTRACT_TYPE,$params);
        $times='';
        if (isset($params['createtime']) && $params['createtime']) {//跟进状态
            $createtime = $params['createtime'];
            $times = setTimes($createtime, 'date');
            $where['order_date'] = ['between', $times];
        }
        if ($name) {
            $where['num'] = ['like', "%{$name}%"];
        }
        if ($is_invoice) {
            if ($is_invoice == 1) {
                $where['invoice_file_ids'] = ['neq', ''];
            } else {
                $where['invoice_file_ids'] = ['eq', ''];
            }
        }

        if (isset($params['staff_id']) && $params['staff_id']) {//下级员工筛选
            $where['owner_staff_id'] = $params['staff_id'];
        } else {
            if (isset($params['type']) && $params['type']) {//客户分类
                if ($params['type'] == 1) {//我的客户
                    $where['owner_staff_id'] = $this->auth->id;
                } elseif ($params['type'] == 2) {//下属负责的客户
                    $where['owner_staff_id'] = ['in', Staff::getLowerStaffId()];
                }else{
                    $where['owner_staff_id'] = ['in', Staff::getMyStaffIds()];
                }
            } else {
                $where['owner_staff_id'] = ['in', Staff::getMyStaffIds()];

            }
        }
        //审核状态 1审核中、2审核通过、3审核未通过
        if (isset($params['check_status']) && $params['check_status']) {
            //0待审核、1审核中、2审核通过、3审核未通过、4撤销
            if ($params['check_status'] == 1) {
                $where['check_status'] = ['in', [0, 1]];
            } elseif ($params['check_status'] == 2) {
                $where['check_status'] = 2;
            } elseif ($params['check_status'] == 3) {
                $where['check_status'] = 3;
            } elseif ($params['check_status'] == 4) {
                $where['check_status'] = 4;
            } elseif ($params['check_status'] == 9) {
                $where['check_status'] = 9;
            }
        }
        if ($customer_id) {
            $where['customer_id'] = $customer_id;
        }
        if (isset($params['id_list'])) {//日志 查询id列表
            $where = [];
            $where['id'] = ['in', explode(',', $params['id_list'])];
        }

        $records = ContractModel::where($where)->with([
            'customer',
            'contacts',
            'ownerStaff',
            'orderStaff',
            'receivables'
        ])->order('id desc')->paginate($limit)->toArray();

        $data = $records['data'];
        $contractId = '';
        foreach ($data as $k => $v) {
            if (empty($v['receivables'])) {
                $v['receivables'] = [
                    'repayment_money' => 0,
                    'be_money' => $v['money'],
                    'ratio' => 0
                ];
            } else {
                $be_money = $v['money'] - $v['receivables']['repayment_money'];
                $be_ratio = 0;
                if($v['money'] > 0){
                    $be_ratio = round($v['receivables']['repayment_money'] / $v['money'] * 100, 2);
                }
                $v['receivables'] = [
                    'repayment_money' => $v['receivables']['repayment_money'],
                    'be_money' => ($be_money > 0) ? $be_money : 0,
                    'ratio' => $be_ratio
                ];
            }
            $data[$k] = $v;
            $contractId = $v['id'].','.$contractId;
        }
        $whereT['contract_id']=array('in',$contractId);
        $noMoney = ContractModel::where($where)->sum('money');
        $moneyinfo['repayment_money'] = Receivables::where($whereT)->where(array('check_status'=>2))->sum('money'); //已回款
        $moneyinfo['be_money'] = sprintf("%.2f",$noMoney)-sprintf("%.2f",$moneyinfo['repayment_money']);//未回款
        $moneyinfo['allmoney'] = $noMoney;//订单总金额

        $this->success('请求成功', [
            'moneyinfo' => $moneyinfo,
            'total' => $records['total'],
            'per_page' => $records['per_page'],
            'current_page' => $records['current_page'],
            'last_page' => $records['last_page'],
            'data' => $data
        ]);
    }


    //获取客户相关订单列表
    public function getCustomerContacts()
    {
        $limit = input("limit/d", 10);
        $customer_id = input('customer_id');
        $contacts_id = input('contacts_id');
        $where = [];
        if ($customer_id) {
            $where['customer_id'] = $customer_id;
        }
        if ($contacts_id) {
            $where['contacts_id'] = $contacts_id;
        }
        $records = ContractModel::where($where)->with(['receivables'])
            ->field('id,name,money,num,check_status')->order('id desc')->select();

        $records = collection($records)->toArray();
        foreach ($records as $k => $v) {
            if (empty($v['receivables'])) {
                $v['receivables'] = [
                    'repayment_money' => 0,
                    'be_money' => $v['money'],
                    'ratio' => 0
                ];
            } else {
                $be_money = $v['money'] - $v['receivables']['repayment_money'];
                $be_ratio = 0;
                if($v['money']>0){
                    $be_ratio = round($v['receivables']['repayment_money'] / $v['money'] * 100, 2);
                }
                $v['receivables'] = [
                    'repayment_money' => $v['receivables']['repayment_money'],
                    'be_money' => ($be_money > 0) ? $be_money : 0,
                    'ratio' => $be_ratio
                ];
            }
            $records[$k] = $v;
        }
        $this->success('请求成功', $records);
    }


    //获取订单详情
    public function getDetail()
    {
        $id = input('id');
        $contract = ContractModel::where(['id' => $id])->with([
            'customer',
            'contacts',
            'business',
            'ownerStaff',
            'orderStaff',
            'product',
            'receivables'
        ])->find();
        if (empty($contract)) {
            $this->error('订单不存在');
        }
        $contract = $contract->toArray();
        $contract = ContractOther::getOther($contract);
        $receivablesMoney = Receivables::where(['contract_id' => $contract['id'], 'check_status' => 2])->sum('money');
        //回款金额
        $contract['receivables_money'] = $receivablesMoney;
        if ($contract['check_status'] == 0 || $contract['check_status'] == 1) {
            $contract['is_examine'] = ExamineRecord::isExaminse(ExamineRecord::CONTRACT_TYPE, $id);
        } else {
            $contract['is_examine'] = 0;
        }
        $contract['ratios'] = json_decode($contract['ratios'],true);
        if($contract['ratios']){
            foreach ($contract['ratios'] as $k => $v) {
                $v['staff'] = Staff::where(['id' => $v['staff_id']])->field('id,name,img,post')->find()->toArray();
                $v['money'] = round($contract['money'] * ($v['ratio'] / 100),2);
                $contract['ratios'][$k] = $v;
            }
        }
        if (empty($contract['receivables'])) {
            $contract['receivables'] = [
                'repayment_money' => 0,
                'be_money' => $contract['money'],
                'ratio' => 0
            ];
        } else {
            $be_money = $contract['money'] - $contract['receivables']['repayment_money'];
            $be_ratio = 0;
            if($contract['money']>0){
                $be_ratio = round($contract['receivables']['repayment_money'] / $contract['money'] * 100, 2);
            }
            $contract['receivables'] = [
                'repayment_money' => $contract['receivables']['repayment_money'],
                'be_money' => ($be_money > 0) ? $be_money : 0,
                'ratio' => $be_ratio
            ];
        }
        $contract['is_operation'] = 0;

        if ($contract['owner_staff_id'] == $this->auth->id) {
            //是否可以操作
            $contract['is_operation'] = 1;
        }

        //标记通知已读
        Message::setRead(Message::CONTRACT_TYPE, $id, $this->auth->id);

        $this->success('请求成功', $contract);
    }

    //获取修改后的订单详情
    public function getContractDetail()
    {
        $id = input('id');
        $contract = ContractModel::where(['id' => $id])->with([
            'customer', 'contacts', 'ownerStaff', 'orderStaff', 'product', 'receivables'
        ])->find();
        if (empty($contract)) {
            $this->error('订单不存在');
        }
        $contract = $contract->toArray();
        $contract = ContractOther::getOther($contract);
        $receivablesMoney = Receivables::where(['contract_id' => $contract['id'], 'check_status' => 2])->sum('money');
        //回款金额
        $contract['receivables_money'] = $receivablesMoney;
        if ($contract['check_status'] == 0 || $contract['check_status'] == 1) {
            $contract['is_examine'] = ExamineRecord::isExaminse(ExamineRecord::CONTRACT_TYPE, $id);
            $examine = ExamineRecord::where([
                'relation_type' => ExamineRecord::CONTRACT_TYPE,
                'relation_id' => $id,
                'status' => 0,
            ])->find();;
            $contract['examine'] = json_decode($examine['edit_field']);
        } else {
            $contract['is_examine'] = 0;
        }
        if (empty($contract['receivables'])) {
            $contract['receivables'] = [
                'repayment_money' => 0,
                'be_money' => $contract['money'],
                'ratio' => 0
            ];
        } else {
            $be_money = $contract['money'] - $contract['receivables']['repayment_money'];
            $be_ratio = 0;
            if($contract['money'] > 0){
                $be_ratio = round($contract['receivables']['repayment_money'] / $contract['money'] * 100, 2);
            }
            $contract['receivables'] = [
                'repayment_money' => $contract['receivables']['repayment_money'],
                'be_money' => ($be_money > 0) ? $be_money : 0,
                'ratio' => $be_ratio
            ];
        }
        $contract['is_operation'] = 0;

        if ($contract['owner_staff_id'] == $this->auth->id) {
            //是否可以操作
            $contract['is_operation'] = 1;
        }

//标记通知已读
        Message::setRead(Message::CONTRACT_TYPE, $id, $this->auth->id);

        $customerProducts = CustomerProduct::where(['contract_id' => $contract['id']])->with(['product'])->select();
        $contract['customer_product'] = $customerProducts;

        $this->success('请求成功', $contract);
    }

    //修改订单
    public function editReviewedContract()
    {
        $id = input('id');
        $params = $this->request->post();

        $row = ContractModel::where(['id' => $id, 'check_status' => 2])->find();
        if (empty($row)) {
            $this->error('订单信息不存在');
        }
        // 表单验证
        if (($result = $this->qingdongamsValidate($params, get_class(), 'create')) !== true) {
            $this->error($result);
        }
        Db::startTrans();
        try {
            $result = ContractModel::updateReviewedContract($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('提交修改信息成功');
    }


    //获取附件列表
    public function getFilesList()
    {
        $id = input('contract_id');

        $files = ContractFile::where(['contract_id' => $id])->field('file_id')->with(['file'])->select();
        $this->success('请求成功', $files);
    }

    //添加附件
    public function addFiles()
    {
        $contract_id = input('contract_id');
        $files = input('files');

        $files = ContractFile::addFiles($files, $contract_id);
        if($files){
            $this->success('添加成功');
        }
        $this->error('添加失败');
    }

    //删除附件
    public function deleteFiles()
    {
        $id = input('id');

        $files = ContractFile::where(['file_id' => $id])->delete();
        if($files){
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }

    //撤回审核
    public function cancel()
    {
        $id = input('id');
        $contract = ContractModel::where(['id' => $id, 'check_status' => ['in', [0, 1]]])->find();
        if (empty($contract)) {
            $this->error('订单信息不存在');
        }
        if($contract['owner_staff_id'] != $this->auth->id){
            $this->error('只有订单负责人可以撤回审核');
        }
        $record = ExamineRecord::where([
            'relation_type' => ExamineRecord::CONTRACT_TYPE,
            'relation_id' => $id,
            'status' => 0
        ])->find();
        Db::startTrans();
        try {
            if ($message = Message::where([
                'relation_type' => 'examine',
                'relation_id' => $record['id'],
                'from_staff_id' => $this->auth->id
            ])->find()) {
                Message::where(['id' => $message['id']])->update(['status' => 1, 'read_time' => time()]);
            }
            ContractModel::where(['id' => $id])->update(['check_status' => 4, 'flow_staff_ids' => '']);
            ExamineRecord::where([
                'relation_type' => ExamineRecord::CONTRACT_TYPE,
                'relation_id' => $id,
                'status' => 0
            ])->update(['status' => 3]);

            OperationLog::createLog(OperationLog::CONTRACT_TYPE, $id, '撤回审批');
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();;
            $this->error($e->getMessage());
        }


        $this->success('撤回成功');
    }

    //修改订单
    public function editContract()
    {
        $id = input('id');
        $params = $this->request->post();
        $row = ContractModel::where(['id' => $id, 'check_status' => ['in', [3, 4]]])->find();
        if (empty($row)) {
            $this->error('订单信息不存在');
        }
        // 表单验证
        if (($result = $this->qingdongamsValidate($params, get_class(), 'create')) !== true) {
            $this->error($result);
        }
        $result = FormField::checkFields(FormField::CONTRACT_TYPE,$params,$id);
        if ($result !== true) {
            $this->error($result);
        }
        Db::startTrans();
        try {
            $result = ContractModel::updateContract($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('修改订单信息成功');
    }

    //修改订单乙方信息
    public function editContractPartyB()
    {
        $id = input('id');
        $params = $this->request->post();
        $row = ContractModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('订单信息不存在');
        }

        Db::startTrans();
        try {
            $result = ContractModel::updateContractPartyB($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('修改订单信息成功');
    }

    //修改订单地址
    public function editContractAddress()
    {
        $id = input('id');
        $params = $this->request->post();
        $row = ContractModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('订单信息不存在');
        }

        Db::startTrans();
        try {
            $result = ContractModel::updateContractAddress($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('修改订单信息成功');
    }

    //下载订单
    public function downloadContract()
    {
        $id = input('id');
        $type = input('type', 'word');
        $contract = ContractModel::where(['id' => $id])
            ->with(['customer', 'contacts', 'orderStaff'])->find();
        if (empty($contract)) {
            $this->error('不能为空');
        }

        $contract = $contract->toArray();

        $contractProduct = ContractProduct::where(['contract_id' => $id])->with(['product'])->select();

        $tmp = new TemplateProcessor('assets/addons/qingdongams/phpword/contract.docx');
        \PhpOffice\PhpWord\Settings::setCompatibility(true);
        \PhpOffice\PhpWord\Settings::setOutputEscapingEnabled(true);


        $tmp->setValue('number', $contract['num']);//订单编号
        $tmp->setValue('name', $contract['customer']['name']);//乙方
        $tmp->setValue('signing_time', date('Y年m月d日', strtotime($contract['order_date'])));//签订时间
        $tmp->setValue('signed_at', $contract['signed_at']);//签订地点

        $rows = count($contractProduct);//总行数
        $tmp->cloneRow('one', $rows);//复制行

        for ($i = 0; $i < $rows; $i++) {
            $tmp->setValue("one#" . ($i + 1), $contractProduct[$i]['name'] ?? '');//名称
            $tmp->setValue("two#" . ($i + 1), $contractProduct[$i]['num'] ?? '');//型号
            $tmp->setValue("three#" . ($i + 1), $contractProduct[$i]['number'] ?? '');//数量
            $tmp->setValue("four#" . ($i + 1),
                $contractProduct[$i]['price'] * $contractProduct[$i]['number']);//总价格
        }


        $tmp->setValue("address", $contract['customer']['address']);//金额
        $tmp->setValue("discount_rate", $contract['discount_rate']);//金额
        $tmp->setValue("price", $contract['money']);//金额
        $tmp->setValue("price_big", convertAmountToCn($contract['money']));//汉字金额
        $tmp->setValue("remarks", $contract['remarks']);//备注
        $tmp->setValue("payment", $contract['payment_text'] . $contract['tax_text']);//支付方式
        $tmp->setValue("be_overdue", $contract['be_overdue']);//到期条款
        $tmp->setValue("delivery_time", $contract['delivery_time']);//
        $tmp->setValue("account", $contract['collection_account']);//
        $tmp->setValue("account_name", $contract['collection_name']);//
        $tmp->setValue("bank_name", $contract['collection_deposit']);//
        $tmp->setValue("effective", $contract['effective']);//
        $tmp->setValue("guarantee", $contract['guarantee']);//
//        $tmp->setValue("address", $contract['customer']['address']);//
        $tmp->setValue("legal", $contract['legal']);//
        $tmp->setValue("entrust", $contract['entrust']);//
        $tmp->setValue("handler", $contract['handler']);//
        $tmp->setValue("mobile", $contract['mobile']);//
        $tmp->setValue("fax", $contract['fax']);//
        $tmp->setValue("deposit", $contract['deposit']);//
        $tmp->setValue("y_account", $contract['account']);//
        $tmp->setValue("order_name", $contract['order_staff']['name']);//
        $tmp->setValue("order_mobile", $contract['order_staff']['mobile']);//
        //end 配置

        $filename = $contract['customer']['name'] . $contract['num'] .'-'.date('His'). '.docx';
        $fileurl = './uploads/' . date('Ymd') . '/';
        if (!file_exists($fileurl)) {
            mkdir($fileurl);
        }

        $tmp->saveAs($fileurl . $filename);//另存为


        $model = new \addons\qingdongams\model\File();
        $data = [
            'types' => 'file',
            'name' => $filename,
            'save_name' => $fileurl . $filename,
            'size' => filesize($fileurl . $filename),
            'file_path' => trim($fileurl, '.') . $filename,
        ];

        $model->save($data);
        $lastid = $model->getLastInsID();


        $file = cdnurl($model::getUrl($lastid), true);
        if ($type == 'pdf') {
            $docfile = $_SERVER['DOCUMENT_ROOT'] . trim($data['save_name'], '.'); // word文件
            $pdfdir = $_SERVER['DOCUMENT_ROOT'] . trim($fileurl, '.'); // pdf文件
            $cmd = "export HOME=/tmp && libreoffice --headless -convert-to pdf {$docfile} -outdir {$pdfdir}";
            @exec($cmd);
            $pathinfo = pathinfo($file);
            $file = $pathinfo['dirname'] . '/' . $pathinfo['filename'] . '.pdf';
            $filename = $pathinfo['filename'] . '.pdf';
        }

        OperationLog::createLog(OperationLog::CONTRACT_TYPE, $id, '下载订单');
        $this->success('请求成功', ['file' => $file, 'id' => $lastid, 'filename' => $filename]);
    }


    //获取账户列表
    public function getAccountList()
    {
        $accounts = Account::where(['status'=>1])->select();
        $this->success('请求成功', $accounts);
    }

    //订单生效
    public function startContract()
    {
        $id = input('contract_id');
        $row = ContractModel::get($id);
        if (empty($row)) {
            $this->error('订单信息不存在');
        }

        $model = new ContractModel();
        $contract = $model->get($id);
        $files = $model->where(['id' => $id])->update(['is_start' => 1]);

        $product = ContractProduct::where(['contract_id' => $row['id']])->select();
        $customerInfo = \addons\qingdongams\model\Customer::get($row['customer_id']);

        //自动发货审批人
        $addWorkorder = [
            'workorder_number' => \addons\qingdongams\model\Workorder::getWorkorderNumber(),
            'workorder_type' => '产品发货',
            'title' => '产品发货',
            'customer_id' => $customerInfo['id'],
            'contacts_id' => $row['contacts_id'],
            'address' => $customerInfo['address'],
            'address_detail' => $customerInfo['address_detail'],
            'lng' => $customerInfo['lng'],
            'lat' => $customerInfo['lat'],
            'priority' => '一般',
            'create_staff_id' => $row['create_staff_id'],
            'owner_staff_id' => $row['owner_staff_id'],
            'product' => $product,
            'delivery_address' => $contract['delivery_address'],
            'delivery_address_detail' => $contract['delivery_address_detail'],
            'consignee' => $contract['consignee'],
            'consignee_mobile' => $contract['consignee_mobile'],

        ];
        \addons\qingdongams\model\Workorder::createWorkorder($addWorkorder);

        OperationLog::createLog(OperationLog::CONTRACT_TYPE, $id, '客户已确认');
        $this->success('操作成功', $files);
    }

    //终止订单
    public function revokeContract()
    {
        $id = input('contract_id');
        $model = new ContractModel();
        $row = $model->get($id);
        if (empty($row)) {
            $this->error('信息不存在');
        }
        if($row['owner_staff_id'] != $this->auth->id){
            $this->error('只有订单负责人可以终止订单');
        }
        $files = $model->where(['id' => $id])->update(['contract_status' => 2, 'check_status' => 9]);
        Message::addMessage(Message::CONTRACT_TYPE, $id, $row['owner_staff_id'], $this->auth->id, "订单《{$row['num']}》被终止，请您及时查看！");

        OperationLog::createLog(OperationLog::CONTRACT_TYPE, $id, '终止订单');
        $this->success('操作成功', $files);
    }

    //回执订单
    public function receiptContract()
    {
        $params = $this->request->post();
        if (empty($params['id'])) {
            $this->error('id不能为空');
        }
        if (empty($params['receipt_file_ids'])) {
            $this->error('回执单不能为空');
        }
        if (empty($params['receipt_date'])) {
            $this->error('回执时间不能为空');
        }

        Db::startTrans();
        try {
            $result = ContractModel::receiptContract($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('回执成功');
    }

    //发票物流
    public function invoiceContract()
    {
        $params = $this->request->post();
        if (empty($params['id'])) {
            $this->error('id不能为空');
        }
        if (empty($params['invoice_file_ids'])) {
            $this->error('发票附件不能为空');
        }
        if (empty($params['invoice_date'])) {
            $this->error('时间不能为空');
        }
        if (empty($params['invoice_logistics_number'])) {
            $this->error('单号不能为空');
        }

        Db::startTrans();
        try {
            $result = ContractModel::invoiceContract($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('回执成功');
    }


    //获取支付类型文字
    public function getPayTypeText()
    {
        $money = input('money');
        $type = input('type');
        if ($type == '五五') {
            $money = $money / 2;
            $cnMoney = convertAmountToCn($money);
            $content = "订单生效后，发货前，乙方须在当天内预付订单总价定金50%￥{$money}（人民币大写：{$cnMoney}），安装调试合格后，乙方须在当天内付清订单总价尾款50%￥{$money}（人民币大写：{$cnMoney}）";
        } elseif ($type == '三六一') {
            $money1 = ($money / 10) * 3;
            $cnMoney1 = convertAmountToCn($money1);
            $money2 = ($money / 10) * 6;
            $cnMoney2 = convertAmountToCn($money2);
            $money3 = ($money / 10) * 1;
            $cnMoney3 = convertAmountToCn($money3);
            $content = "订单生效后，乙方须在当天内预付订单总价定金30%￥{$money1}（人民币大写：{$cnMoney1}），发货前，乙方须在当天内预付订单总价货款60%￥{$money2}（人民币大写：{$cnMoney2}），设备安装调试后，乙方须在当天内付清订单总价尾款10%￥{$money3}（人民币大写：{$cnMoney3}）。";
        } elseif ($type == '三七') {
            $money1 = ($money / 10) * 3;
            $cnMoney1 = convertAmountToCn($money1);
            $money2 = ($money / 10) * 7;
            $cnMoney2 = convertAmountToCn($money2);
            $content = "订单生效后，发货前，乙方须在当天内预付订单总价定金30%￥{$money1}（人民币大写：{$cnMoney1}），安装调试合格后，乙方须在当天内付清订单总价尾款70%￥{$money2}（人民币大写：{$cnMoney2}）。";
        } else {
            $content = '';
        }

        $this->success('请求成功', $content);
    }


    /**
     * 获取业绩分割比例
     */
    public function getRatio()
    {
        $ratios = Ratio::where(['status' => 1])->field('name,ratio')->select();
        $ratios = collection($ratios)->toArray();
        foreach ($ratios as $k => $v) {
            $v['ratio'] = json_decode($v['ratio'], true);
            $ratios[$k] = $v;
        }
        $this->success('请求成功', $ratios);
    }
}
